package UIFree.controls
{
	import UIFree.uif_component;
	
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class uif_baseCheckBox extends uif_label {
		public var group			: String;
		private var _checked		: Boolean;
		public static const CHECKED	: String = 'CHECKED';
		
		public function uif_baseCheckBox(parent:uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0, styleClass: Object='') {
			super(parent, ax, ay, awidth, aheight, styleClass);
			addEvent(MouseEvent.CLICK, doRelease);
		}
		
		protected function doRelease(e: Event): void {
			if (group) checked = true;
		}
		
		public function get checked(): Boolean {
			return _checked;
		}
		
		protected function changeChecked(a_checked: Boolean): void {
			if (_checked != a_checked) {
				_checked = a_checked;
				dispatchEvent(new Event(Event.CHANGE));
				if (checked && parent) {
					forEachCb(function(child: uif_baseCheckBox, i: int): void {
						if ((child != This) && child.checked) child.checked = false;	
					});
					dispatchEvent(new Event(CHECKED, true, true));
				}
			}
		}
		
		public function set checked(a_checked: Boolean): void {
			changeChecked(a_checked);
		}
		
		public function forEachCb(doProc: Function): void {
			for (var i: uint=0; i<parent.numChildren; i++) {
				var child: uif_baseCheckBox = parent.getChildAt(i) as uif_baseCheckBox;
				if ((child != null) && ((child.group == group) || (!child.group))) {
					doProc(child, i);
				}
			}
		}
		
		public function get checkedIndex(): int {
			var index		: int = 0;
			var ret_index	: int = -1;
			forEachCb(function(child: uif_baseCheckBox, i: int): void {
				if (child.checked) ret_index = index;	
				index++;
			});
			return ret_index;
		}
		
		public static function getCheckedButton(parent: uif_component, group: String=''): uif_baseCheckBox {
			var cb: uif_baseCheckBox = null;
			parent.forEach(function(item: Object): void {
				var a_cb: uif_baseCheckBox = item as uif_baseCheckBox;
				if (a_cb && 
					(!group || (a_cb.group == group)) && 
					(a_cb.checked)) cb = a_cb;
			});
			return cb;
		}
	}
}